package com.wzw.expression.expression.invocation;

import com.wzw.expression.expression.operation.Operation;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author Wangzhiwen
 */
public class OperationInvocationContexts {
    private final MultiValueMap<Class<? extends Operation>, OperationInvocationContext> contexts = new LinkedMultiValueMap<>(16);

    public OperationInvocationContexts() {

    }

    public void addContext(OperationInvocationContext context) {
        contexts.add(context.getMetadata().getOperation().getClass(), context);
    }

    public List<OperationInvocationContext> get(Class<? extends Operation> operationClass) {
        List<OperationInvocationContext> operationInvocationContexts = this.contexts.get(operationClass);
        if (Objects.isNull(operationInvocationContexts)) {
            return Collections.emptyList();
        }
        return operationInvocationContexts;
    }

    public OperationInvocationContext filterOne(Class<? extends Operation> operationClass) {
        List<OperationInvocationContext> operationInvocationContexts = get(operationClass);
        if (operationInvocationContexts.isEmpty()) {
            return null;
        }
        Optional<OperationInvocationContext> first = operationInvocationContexts.stream().filter(v -> v.getMetadata().getOperation().getClass().isAssignableFrom(operationClass)).findFirst();
        return first.orElse(null);
    }

}
